package com.example.Lezedata.ui.activity.goods;

import com.example.Lezedata.R;
import com.example.Lezedata.dataModel.GoodsProjectModel;
import com.example.Lezedata.dataModel.LotteryInfo;
import com.example.Lezedata.net.GBError;
import com.example.Lezedata.net.GBNetRequest;
import com.example.Lezedata.net.ServerResponseObserver;
import com.example.Lezedata.ui.activity.baseClass.GBBaseVc;
import com.example.Lezedata.ui.activity.common.GBCell;
import com.example.Lezedata.ui.activity.history.HistoryVc;
import com.example.Lezedata.ui.fragment.BaseFragment;
import com.example.Lezedata.ui.fragment.commonfragment.GBBuyGoodsView;
import com.example.Lezedata.ui.fragment.commonfragment.GBLotteryView;
import com.example.Lezedata.ui.fragment.goodsDetail.GoodsDetailHeadViewFragment;
import com.example.Lezedata.util.GBInterface;
import com.example.Lezedata.util.GBUtil;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import java.util.ArrayList;

import bid.Bid;
import common.Common;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

public class ProductDetail extends GBBaseVc {
    private int pageStart = 0;
    private int pageSize = 20;
    private ListView listView;
    private TextView bidNowTextView;
    ArrayList<Bid.BidRecordItem> bidRecordItems = new ArrayList<>();
    private BaseAdapter adapter;
    private GoodsProjectModel projectModel = GoodsProjectModel.testGoodsProjectModel();

    private Bid.BidDetailResponse detailResponse;

    private GoodsDetailHeadViewFragment headViewFragment;
    private GBBuyGoodsView buyGoodsView;
    private GBLotteryView lotteryView;
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initView();
        initAdapter();
        addHeadView();
        addAction();

        setTitle("Product Detail");
        getContentView().setVisibility(View.INVISIBLE);
        loadData();
    }

    void loadDataComplete(){
        headViewFragment.setDetailResponse(detailResponse);
        switch (detailResponse.getStatus()){
            case BS_STORE:// 库存
            case BS_ACTIVE://活动中
            case BS_DONE://已结束
                listView.removeHeaderView(listView.findViewWithTag("lotteryView_line"));
                removeFragment(lotteryView);
                break;
            case BS_DRAW://已经开奖
                lotteryView.setBidRecordItem(detailResponse.getDrawBidRecord());
                break;
        }
    }

    // 添加头部View
    void addHeadView(){
        headViewFragment = new GoodsDetailHeadViewFragment();
        headViewFragment.goodsProjectModel = projectModel;
        headViewFragment.viewCreatedListener = new GBInterface() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onViewCreated(View view) {
                listView.addHeaderView(view);
                addDiverLine();
                addLottery();
            }
        };
        getSupportFragmentManager().beginTransaction().add(headViewFragment,"GoodsDetailHeadViewFragment").commit();
    }

    // 添加中奖者View
    void addLottery(){
        lotteryView = new GBLotteryView();
        lotteryView.viewCreatedListener = new GBInterface() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onViewCreated(View view) {
                listView.addHeaderView(view);
                TextView line = addDiverLine();
                line.setTag("lotteryView_line");
                addHistory();
            }
        };
        getSupportFragmentManager().beginTransaction().add(lotteryView,"GoodsDetailHeadViewFragment").commit();
    }

    void removeFragment(BaseFragment fragment){
        listView.removeHeaderView(fragment.contentView);
        getSupportFragmentManager().beginTransaction().remove(fragment);
    }

    // 添加历史中奖者
    @RequiresApi(api = Build.VERSION_CODES.M)
    void addHistory(){
        View view = LayoutInflater.from(this).inflate(R.layout.activity_prodetail_history,null,false);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, HistoryVc.class);
                intent.putExtra("goodsId","goodsId");
                jumpActivityIntent(intent);
            }
        });
        listView.addHeaderView(view);
        addDiverLine();
        addProductDetail();
    }

    // 添加产品详情点击条
    @RequiresApi(api = Build.VERSION_CODES.M)
    void addProductDetail(){
        GBCell cell = GBCell.newInstance(mContext);
        cell.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ProductDetailVc.class);
                intent.putExtra("goodsId",detailResponse.getGoodsId());
                jumpActivityIntent(intent);
            }
        });
        cell.setString("Product Detail");
        cell.setLeftDrawable(getDrawable(R.drawable.product_product_detail));
        listView.addHeaderView(cell);
        addDiverLine();
        adapter.notifyDataSetChanged();
    }

    // view init
    void initView(){
        listView = findViewById(R.id.goodsDetail_listView);
        bidNowTextView = findViewById(R.id.BidNow);
        findViewById(R.id.floatingActionButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listView.smoothScrollToPositionFromTop(0,0,250);
            }
        });
    }

    // 添加view 事件
    void addAction(){
        bidNowTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bidNow(v);
            }
        });
    }

    /// 购买 下标
    public void bidNow(View view){
        showBuyView();
    }

    // 弹出购买框
    void showBuyView(){
        buyGoodsView = new GBBuyGoodsView();
        buyGoodsView.viewCreatedListener = new GBInterface() {
            @Override
            public void onViewCreated(View view) {
                buyGoodsView.setDetailResponse(detailResponse);
            }
        };
        buyGoodsView.show(getSupportFragmentManager(),"234");
    }

    // 获取id
    String getBid(){
        String bid = getIntent().getStringExtra("bid");
        if (bid == null){
            bid = "";
        }
        return bid;
    }

    // 获取数据
    void loadData(){
        hudShow();
        Common.Id id = Common.Id.newBuilder().setId(getBid()).build();
        ServerResponseObserver observer = new ServerResponseObserver(new ServerResponseObserver.requestListener<Bid.BidDetailResponse>() {
            @Override
            public void complete(Bid.BidDetailResponse value, GBError t) {
                hudDismiss();
                getContentView().setVisibility(View.VISIBLE);
                if (t == null){
                    detailResponse = value;
                    loadDataComplete();
                }else {
                    addErrorView();
                }
            }
        });
        GBNetRequest.stub().bidDetail(id,observer);
        loadBidHistoryList();
    }

    // 获取历史投标记录
    void loadBidHistoryList(){
        final Common.PageInfo pageInfo = Common.PageInfo.newBuilder().setPageStart(pageStart).setPageSize(pageSize).build();
        GBNetRequest.stub().bidRecordList(Bid.IdPageRequest.newBuilder().setId(getBid()).setPageInfo(pageInfo).build(),
                ServerResponseObserver.observer(new ServerResponseObserver.requestListener<bid.Bid.BidRecordListResponse>() {
                    @Override
                    public void complete(bid.Bid.BidRecordListResponse value, GBError error) {
                        if (error == null){
                            if (pageInfo.getPageStart() == 0){
                                bidRecordItems.clear();
                            }
                            bidRecordItems.addAll(value.getListList());
                            adapter.notifyDataSetChanged();
                        }
                    }
                })
        );
    }

    void initAdapter(){
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return bidRecordItems.size();
            }

            @Override
            public Bid.BidRecordItem getItem(int position) {
                return bidRecordItems.get(position);
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (position == 0){
                    GBCell cell = GBCell.newInstance(mContext);
                    cell.setRightDrawable(null);
                    cell.setString("Participants");
                    cell.setLeftDrawable(getDrawable(R.drawable.product_participants));
                    return cell;
                }
                if (convertView == null || convertView.getClass() != BuyPersonCell.class){
                    convertView = BuyPersonCell.newInstance(mContext);
                }
                BuyPersonCell personCell = (BuyPersonCell)convertView;
                personCell.setBidRecordItem(getItem(position));
                return convertView;
            }
        };
        listView.setAdapter(adapter);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    TextView addDiverLine(){
        TextView line = new TextView(mContext);
        line.setHeight(GBUtil.dpTo2px(mContext,10));
        line.setBackground(new ColorDrawable(getColor(R.color.app_color_inputBackground)));
        listView.addHeaderView(line);
        return line;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.product_toolbar_menu, menu);
        setMenu();
        return super.onCreateOptionsMenu(menu);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    void setMenu(){
        setOnMenuItemClickListener(new androidx.appcompat.widget.Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.rule:

                        break;
                    case R.id.qa:

                        break;
                }
                return false;
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_product_detail;
    }
}